import Taro from '@tarojs/taro'
let app = {
  // apiUri: 'http://127.0.0.1/zhongsheng-server/public',
  // imageUri: 'http://127.0.0.1/zhongsheng-server/public/',
  apiUri: 'https://experts.bayou-tech.cn',
  imageUri: 'https://experts.bayou-tech.cn/',
  // apiUri: 'https://zhongsheng.bayou-tech.cn',
  // imageUri: 'https://zhongsheng.bayou-tech.cn/',
  // wsUri: 'ws://127.0.0.1:8889',
  wsUri: 'wss://byim.bayou-tech.cn',
  current: {id:'1', name:'张三'},
  eyesphoto:'',
  eyesvideo:'',
  eyesfile:'',
  inquiry_answer_id:'',
  dingdanid:'',
  dingdanname:'',
  chatArr:[],
  zixun:{},
  doctorid:'',
  wz_order_id: '',
  wz_doctor_id: '',
  sockets: [],
  sessionKey: '',
  share_page: '',
  scan_doctor_id: '',

  closeSockets() {
    var sockets = this.sockets;
    for (var i = 0; i < sockets.length; i++) {
      var socket = sockets[i];
      socket.close();
    }
    this.sockets = []; 
  },
  getToken: function() {
    // return "eyJpdiI6IlVtRjJ3bTB3VEt0YjJHT3g2bzczUkE9PSIsInZhbHVlIjoiSE41NjJ3aGRtUHRBZmlKRENYK1lIcWVqQXdETGJhS05qYXRCektDcnNYTm03VEtkVDlXY01nTEtpeVFGb2hPbElJejhnNkFHelZsVklxY1plZk5Ub2c9PSIsIm1hYyI6IjQzNGExYTFmM2NlOGEwMDQwMDZkNmNkOWVmMzZmYmYzNDM5NzY5YjM0OGQyMWM3NTVlOTE5NTllYTU3MDgzYTEifQ=="
    return Taro.getStorageSync('token');
  },
  get: function(url, data, callback) {
    data.token = this.getToken();
    Taro.request({
      url: this.apiUri + '/' + url,
      method: 'GET',
      data: data
    }).then(res => {
      callback(res);
    });
  },
  post: function(url, data, callback) {
    data.token = this.getToken();
    Taro.request({
      url: this.apiUri + '/' + url,
      method: 'POST',
      data: data,
      dataType: 'json',
      header: {
        'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }).then(res => {
      callback(res);
    });
  },
  navigateTo: function(url) {
    Taro.navigateTo({
      url: url
    })
  },
  redirectTo: function(url) {
    Taro.redirectTo({
      url: url
    })
  },
  wxLogin: function(doctor_id) {
    var me = this;
    console.log("获取微信code");
    // 登录
    Taro.login({
      success: res => {
        console.log("code="+res.code);
        
        me.post('web/patient/wx_login', { code: res.code}, function(res) {
          console.log('微信信息');
          if (res.data.status == 200) {
            Taro.setStorageSync('token', res.data.result.data);
            me.current = res.data.result.info;
            me.sessionKey = res.data.result.session_key;
            console.log(me.current);
            // 是否授权登录 
            if (me.isEmpty(me.current.head_image)) {
              console.log('跳转去授权页面');
              // me.redirectTo('/pages/authlogin/authlogin');
              me.redirectTo('/pages/firstEntry/firstEntry')
            } else if (me.isEmpty(me.current.phone)) {
              console.log('跳去获取手机号码页面'); 
              me.redirectTo('/pages/firstEntry/firstEntry')
              // me.redirectTo('/pages/authphone/authphone');
            } else {
              console.log('已授权，跳转去其他页面');
              
              me.decidePage();
            }
          }
        })
      }
    })
  },
  decidePage: function() {
    var me = this;
    console.log(wx.getLaunchOptionsSync())
    let obj = wx.getLaunchOptionsSync()
    // console.log(obj.referrerInfo.appId == false)
    //  obj.referrerInfo.appId = 1
    // let a = JSON.stringify(obj.referrerInfo)
    // console.log(a)
    // me.alertTab(a)
    if(obj.referrerInfo.appId){
        let data = {}
        data.labelName = obj.referrerInfo.appId,
        data.source = '公众号'
        data.appid = obj.referrerInfo.appId
        me.post('user_label/autoLabel',data,function(res){
            console.log(res)
        })
    }
    //     me.alertTab('非公众号')
    // }
    if (!this.isEmpty(this.share_page)) {
      console.log('转发页面');
      var page = this.share_page;
      this.share_page = '';
      this.redirectTo(page);
    } else if (!this.isEmpty(this.scan_doctor_id)) {
      console.log('扫码页面');
      var doctor_id = this.scan_doctor_id;
      this.scan_doctor_id = '';
      app.get('web/patient/is_has_health_archive', {}, function(res) {
        var data = res.data;
        console.log(res)
        if (data.status == 200 && data.result.is_has) {
          me.redirectTo('/pages/center/pages/wanshanxinxi/wanshanxinxi?doctor_id='+doctor_id);
        } else {
          me.redirectTo('/pages/eyeDoctor/eyeDoctor');
        }
      })
    } else {
      // this.redirectTo('/pages/blank/blank'); // 生产打开
      this.redirectTo('/pages/eyeDoctor/eyeDoctor'); // 开发打开
    }
  },
  //弹出提示框,只有确认的警告框
  alertTab:function(contentText){
    Taro.showModal({
      title: '提示',
      content:contentText,
      showCancel: false
    });
  },
  //解析返回的字符串对象
  transObjStr:function(str){
    let arr=str.substr(1,str.length-2).split(',');
    let obj={};
    for(let val of arr){
      let sArr=val.split(':');
      obj[sArr[0]]=sArr[1];
    }
    return obj;
  },
  //用于弹出提示框来判断
  isConfirm:function(text,success,fail){
    Taro.showModal({
      title:'提示',
      content:text,
    }).then(res=>{
      if(res.confirm){
         if(success){
           success();
         }
      }else{
        if(fail){
          fail();
        }
      }
    })
  },
  //判断图片路径是否是http开头
  picturejudgment:function(src){
    if(src){
      if(src.substr(0,4)==='http'){
      return src;
    }else{
      return this.imageUri+src;
    }
    }
  },
  getPath: function(path) {
    if (this.isEmpty(path)) {
      return path;
    }
    if (path.indexOf('http://') != -1 || path.indexOf('https://') != -1) {
      return path;
    }
    return this.imageUri + path;
  },
  success: function(title, success) {
    Taro.showToast({
      title: title,
      icon: 'success',
      duration: 1000,
      success: success
    }).then()
  },
  toast: function(title) {
    Taro.showToast({
      title: title,
      icon: 'none',
      duration: 1500
    }).then()
  },
  toastMessage: function(title) {
    Taro.showToast({
      title: title,
      icon: 'none',
      duration: 1500
    }).then()
  },
  isEmpty: function(value) {
    if (value !== 0 && !value) {
      return true;
    }
    if ((value instanceof Array) && value.length <= 0) {
      return true;
    }
    return false;
  },
  checkPoneFormat: function(value) {
    return /^1\d{10}$/.test(value);
  },
  getQueryString(query, key) {
    let arr = query.split('=');
    return arr[1];
  },
  navigateBack: function(url) {
    Taro.navigateBack({
      url: url
    })
  },
  reLaunch: function(url) {
    Taro.reLaunch({
      url: url
    })
  },
  dateFormate(date, fmt) {
    var o = {
        "M+": date.getMonth() + 1, //月份 
        "d+": date.getDate(), //日 
        "h+": date.getHours(), //小时 
        "m+": date.getMinutes(), //分 
        "s+": date.getSeconds(), //秒 
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
        "S": date.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  },
  // 调用小程序支付
  callPayment(obj, success, fail) {
    var me = this;
    wx.requestPayment({
      timeStamp: obj.timeStamp,
      nonceStr: obj.nonceStr,
      package: obj.package,
      signType: obj.signType,
      paySign: obj.paySign,
      success: success,
      fail: fail,
      complete: function(res) {
        console.log(res);
      }
    })
  },
  prviewImage(current_image, images) {
    for (var i = 0; i < images.length; i++) {
      images[i] = this.getPath(images[i]);
    }
    Taro.previewImage({
      urls: images,
      current: current_image
    })
  },
  inArray(arr, value) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == value) {
        return true;
      }
    }
    return false;
  },
  obj_to_query(obj) {
    var query = '';
    for (var key in obj) {
      query += key + '=' + obj[key] + '&';
    }
    return query.slice(0, -1);
  },
  isEmptyObject(obj) {
		for (var key in obj) {
			return false;
    }
    return true;
	}
  
};

export default app;